package com.wondertek.common.util.base;

import cn.hutool.core.util.ObjectUtil;
import com.wondertek.common.exception.AppException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import java.util.Set;
import java.util.function.Consumer;

/**
 * @author xqs
 */
public class ValidateUtil extends cn.hutool.core.lang.Validator{

    private static final jakarta.validation.Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();


    /**
     * 校验对象
     */
    public static <T> void validate(T t) {
        Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(t);
        if (!constraintViolations.isEmpty()) {
            StringBuilder validateError = new StringBuilder();
            for (ConstraintViolation<T> constraintViolation : constraintViolations) {
                validateError.append(constraintViolation.getMessage()).append(",");
            }
            throw new AppException(validateError.toString());
        }
    }


    /**
     * 校验对象特定属性
     */
    public static <T> void validateProperty(T t,String propertyName) {
        Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validateProperty(t,propertyName);
        if (!constraintViolations.isEmpty()) {
            StringBuilder validateError = new StringBuilder();
            for (ConstraintViolation<T> constraintViolation : constraintViolations) {
                validateError.append(constraintViolation.getMessage());
            }
            throw new AppException(validateError.toString());
        }
    }

    public static void isEmpty(Object object,String errMessage){
        if(ObjectUtil.isEmpty(object)){
            throw new AppException(errMessage);
        }
    }

    public static <T> void isEmpty(T t, Consumer<T> consumer){
        if(ObjectUtil.isEmpty(t)){
            consumer.accept(t);
        }
    }

    public static boolean isNotEmpty(Object object){
        return ObjectUtil.isNotEmpty(object);
    }

    public static <T> void isNotEmpty(T t, Consumer<T> consumer){
        if(ObjectUtil.isNotEmpty(t)){
            consumer.accept(t);
        }
    }

    public static boolean isMatchRegex(String regex, CharSequence value){
        return cn.hutool.core.lang.Validator.isMatchRegex(regex,value);
    }

    public static void isMatchRegex(String regex, String value,Consumer<String> consumer){
        if(cn.hutool.core.lang.Validator.isMatchRegex(regex,value)){
            consumer.accept(value);
        }
    }

    public static void isNotMatchRegex(String regex, String value,String errMessage){
        if(!cn.hutool.core.lang.Validator.isMatchRegex(regex,value)){
            throw new AppException(errMessage);
        }
    }

    public static void isNotMatchRegex(String regex, String value,Consumer<String> consumer){
        if(!cn.hutool.core.lang.Validator.isMatchRegex(regex,value)){
            consumer.accept(value);
        }
    }
}
